﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace AntiTheft
{
    public class AntiTheftHandler : IHttpHandler
    {
        #region
        public AntiTheftHandler(System.Web.Routing.RequestContext requestContext)
        {
            ProcessRequest(requestContext);
        }

        private void ProcessRequest(System.Web.Routing.RequestContext requestContext)
        {
            HttpContextBase context = requestContext.HttpContext;
            HttpRequestBase request = context.Request;
            HttpResponseBase response = context.Response;
            HttpServerUtilityBase server = context.Server;

            string imageName = requestContext.RouteData.Values["imagename"].ToString();
            var imageFolder = server.MapPath("~/images/");

            // 检查是否盗链
            string referrer = request.ServerVariables["HTTP_REFERER"];

            response.Clear();
            response.ContentType = "image/jpeg";

            if (referrer != null &&
                referrer.Contains("cnblogs.com"))
            {
                // 设置 MIME
                response.ContentType = GetContentType(request.Url.AbsolutePath);

                // 正常访问
                response.TransmitFile(
                    System.IO.Path.Combine(
                        imageFolder, imageName
                        )
                    );
            }
            else
            {
                // 显示警告图片
                response.TransmitFile(
                    System.IO.Path.Combine(
                        imageFolder, "warnning.png"
                        )
                    );
            }

            response.End();
        }

        private static string GetContentType(string url)
        {
            switch (System.IO.Path.GetExtension(url))
            {
                case ".gif":
                    return "image/gif";
                case ".jpg":
                    return "image/jpeg";
                case ".png":
                    return "image/png";
                default:
                    break;
            }
            return null;
        }

        #endregion

        #region IHttpHandler Members

        public bool IsReusable
        {
            get { return true; }
        }

        public void ProcessRequest(HttpContext context)
        {
            
        }

        #endregion
    }
}